package com.UdpRecieve.secret.log;

import com.UdpRecieve.domain.FileOption;
import com.UdpRecieve.domain.FilePigeonhole;
import com.UdpRecieve.mapper.FileOptionMapper;
import com.UdpRecieve.secret.domain.SecretLableResult;
import com.UdpRecieve.tool.FileUtil;
import com.UdpRecieve.tool.StringUtils;
import com.UdpRecieve.tool.http.HttpClientFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 发送审计系统日志工具类
 */
@Component
public class BianjieLogUtils {
    private static CloseableHttpClient httpClient = HttpClientFactory.INSTANCE();

    private static Logger logger = LoggerFactory.getLogger(BianjieLogUtils.class);

    @Autowired
    private FileOptionMapper fileOptionMapper;

    private static BianjieLogUtils bianjieLogUtils;

    @PostConstruct
    public void init() {
        bianjieLogUtils = this;
        bianjieLogUtils.fileOptionMapper = this.fileOptionMapper;
    }
    /**
     * 发送日志给大边界(密标相关日志)
     *
     * @param filePigeonhole 文件类 object
     * @param secretLableResult 结果类
     *  saveResult  归档结果 int -0不合格 -1合格
     *  文件密级 int -0不合格 -1合格
     *  管理状态 int -0不合格 -1合格
     *  扩展属性 int -0不合格 -1合格
     *  起草人 int -0不合格 -1合格
     *  审批人 int -0不合格 -1合格
     *  解标结果 int -0不合格 -1合格
     *  md5结果 string -成功||失败原因
     */
    public static void sendFileContentForBigBoundaryM(FilePigeonhole filePigeonhole, SecretLableResult secretLableResult) {
        FileOption fileOption = bianjieLogUtils.fileOptionMapper.selectFileOptionList(new FileOption()).get(0);
        String bianjieAddress =fileOption.getBigBoundaryIpAddress();// Global.getConfig("bianjie.address");
        String bianjieport = fileOption.getBigBoundaryPort();//Global.getConfig("bianjie.port");
        //保证发给边界的没有(_加标)的名称
        if (!StringUtils.isEmpty(filePigeonhole.getFileName()) && filePigeonhole.getFileName().contains("_加标")) {
            String fileSourceName =
                    filePigeonhole.getFileName().split("_加标")[0] + filePigeonhole.getFileType();
            filePigeonhole.setFileName(fileSourceName);
        }
        if (fileOption.getIsUploadLog()==0) {
            //System.out.println("=========发送日志给边界审计系统!=========");
        } else {
            CloseableHttpResponse response = null;
            // 创建Post请求
            HttpPost httpPost = new HttpPost("https://" + bianjieAddress + ":" + bianjieport + "/system/prepositive/receivePost");

            // 我这里利用阿里的fastjson，将Object转换为json字符串;
            // (需要导入com.alibaba.fastjson.JSON包)
            List<Object> lists = new ArrayList<Object>(9);
            //TODO 封装传输list
            //文件信息
            lists.add(
                    JSONArray.toJSONString(filePigeonhole)
            );
            //归档结果
            lists.add(
                    secretLableResult.getSave_result()?1:0
            );
            //文件密级
            lists.add(secretLableResult.getSecret_level_isOk());
            //管理状态
            lists.add(secretLableResult.getSecret_status_isOk());
            //扩展属性
            lists.add(secretLableResult.getSecret_extend_isOk());
            //起草人
            lists.add(secretLableResult.getSecret_drafter_isOk());
            //审批人
            lists.add(secretLableResult.getSecret_authority_isOk());
            //解标结果
            lists.add(
                    secretLableResult.getSecret_solve_result()?1:0
            );
            //md5结果
            lists.add(filePigeonhole.getMd5CheckNum());

            String jsonString = JSON.toJSONString(lists);
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");

            try {
                response = httpClient.execute(httpPost);
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                System.out.println("响应状态为:" + response.getStatusLine());
                if (responseEntity != null) {
                    System.out.println("边界审计响应内容长度为:" + responseEntity.getContentLength());
                    System.out.println("边界审计响应内容为:" + EntityUtils.toString(responseEntity));

                }
            } catch (IOException e) {
                System.out.println("边界审计http请求异常-" + bianjieAddress + ":" + bianjieport);
                e.printStackTrace();
            } finally {
                try {
                    if (response != null)
                        response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    public static void sendFileContentForBigBoundaryFM(FilePigeonhole filePigeonhole, SecretLableResult secretLableResult) {
        FileOption fileOption = bianjieLogUtils.fileOptionMapper.selectFileOptionList(new FileOption()).get(0);
        String bianjieAddress =fileOption.getBigBoundaryIpAddress();// Global.getConfig("bianjie.address");
        String bianjieport = fileOption.getBigBoundaryPort();//Global.getConfig("bianjie.port");

        //保证发给边界的没有(_加标)的名称
        if (!StringUtils.isEmpty(filePigeonhole.getFileName()) && filePigeonhole.getFileName().contains("_加标")) {
            String fileSourceName =
                    filePigeonhole.getFileName().split("_加标")[0] + filePigeonhole.getFileType();
            filePigeonhole.setFileName(fileSourceName);
        }
        if (fileOption.getIsUploadLog()==0) {
            //System.out.println("=========发送日志给边界审计系统!=========");
        } else {
            CloseableHttpResponse response = null;
            // 创建Post请求
            HttpPost httpPost = new HttpPost("https://" + bianjieAddress + ":" + bianjieport + "/system/prepositive/receivePost");
            // 我这里利用阿里的fastjson，将Object转换为json字符串;
            // (需要导入com.alibaba.fastjson.JSON包)
            List<Object> lists = new ArrayList<Object>(9);
            //TODO 封装传输list
            //文件信息
            lists.add(
                    JSONArray.toJSONString(filePigeonhole)
            );
            //归档结果
            lists.add(
                    secretLableResult.getSave_result()?1:0
            );

            //文件密级
            lists.add(-1);
            //管理状态
            lists.add(-1);
            //扩展属性
            lists.add(-1);
            //起草人
            lists.add(-1);
            //审批人
            lists.add(-1);
            //解标结果
            lists.add(-1);

            //md5结果
            lists.add(
                    filePigeonhole.getMd5CheckNum()
            );


            String jsonString = JSON.toJSONString(lists);
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");

            try {
                response = httpClient.execute(httpPost);
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                System.out.println("响应状态为:" + response.getStatusLine());
                if (responseEntity != null) {
                    System.out.println("边界审计响应内容长度为:" + responseEntity.getContentLength());
                    System.out.println("边界审计响应内容为:" + EntityUtils.toString(responseEntity));

                }
            } catch (IOException e) {
                System.out.println("边界审计http请求异常-" + bianjieAddress + ":" + bianjieport);
                e.printStackTrace();
            } finally {
                try {
                    if (response != null)
                        response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    public static void main(String[] args) {
        String bianjieAddress = "192.168.1.244";// Global.getConfig("bianjie.address");
        String bianjieport = "8083";//Global.getConfig("bianjie.port");
        HttpPost httpPost = new HttpPost("https://" + bianjieAddress + ":" + bianjieport + "/test01");
        FilePigeonhole filePigeonhole = new FilePigeonhole();
        filePigeonhole.setBytes(FileUtil.readFileToByteArray("C:\\Users\\Administrator\\Desktop\\压缩文件.zip"));
        String jsonString = JSON.toJSONString(filePigeonhole);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        try {
            httpClient.execute(httpPost);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

    }
}